package com.lebang.service;

import com.alibaba.fastjson.JSON;
import com.lebang.component.RedisClient;
import com.lebang.entity.RequestHeaders;
import com.lebang.entity.TaskRewardsRecord;
import com.lebang.entity.member.LbbMember;
import com.lebang.entity.sys.AppMain;
import com.lebang.mapper.AppMainMapper;
import com.lebang.mapper.LbbMemberMapper;
import com.lebang.mapper.LbbMemberRecordMapper;
import com.lebang.mapper.TaskRewardsRecordMapper;
import com.lebang.service.sys.RegisterWhiteImeiService;
import com.lebangweb.common.TextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.lebang.controller.api.member.MemberApi.MEMBER_DATE;

/**
 * @Author: hwq
 * @Date: 2019/7/23 10:07
 * @Version 1.0
 */
@Service
@Slf4j
public class AppMainService {
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private AppMainMapper appMainMapper;
    @Autowired
    private LbbMemberMapper memberMapper;
    @Autowired
    private LbbMemberRecordMapper lbbMemberRecordMapper;
    @Autowired
    private RegisterWhiteImeiService registerWhiteImeiService;
    @Resource
    private TaskRewardsRecordMapper taskRewardsRecordMapper;
    @Autowired
    private DownAppService downAppService;
    private static final String MAIN_SYS_KEY = "sys:main";

    public AppMain selectById(Integer id) {
        return appMainMapper.selectByPrimaryKey(id);
    }

    public int insert(AppMain vo) {
        vo.setCreateTime(LocalDateTime.now());
        vo.setModifyTime(LocalDateTime.now());
        return appMainMapper.insertSelective(vo);
    }

    public int update(AppMain vo) {
        vo.setModifyTime(LocalDateTime.now());
        return appMainMapper.updateByPrimaryKeySelective(vo);
    }

    @Transactional(readOnly = true)
    public List<Map> getSql(String sql) {
        return appMainMapper.getSql(sql);
    }


    /**
     * 取头显示列表
     *
     * @param version APP的版本
     * @param brand   渠道
     * @param userid  用户的ID
     * @param type    类型， 1 顶部列表 ， 2 内容区域的方格列表
     * @return 列表信息
     */
    public List<AppMain> getListAppMain(RequestHeaders requestHeaders, Integer type) {
        List<AppMain> list = null;
        // redis存入的字段名
        String fieldName = requestHeaders.getVersion() + ":" + requestHeaders.getAppStore() + ":" + type;
        // 从缓存里面先取值
        String str = redisClient.hget(MAIN_SYS_KEY, fieldName);
        if (str != null && !TextUtil.isEmpty(str)) {
            list = JSON.parseArray(str, AppMain.class);
        } else {
            list = appMainMapper.getSon(type, requestHeaders.getAppStore(), requestHeaders.getVersion());
            if (list != null && list.size() > 0) {
                redisClient.hset(MAIN_SYS_KEY, fieldName, JSON.toJSONString(list));
            }
        }
        //设备号不存在白名单
        if (!registerWhiteImeiService.getImei(requestHeaders.getImei())) {
            LbbMember member=memberMapper.selectByImei(requestHeaders.getImei());
            if (member!=null){
                if (!member.getMemberId().equals(requestHeaders.getUserid())){
                    list = list.stream().filter(appMain -> !"新手任务".equals(appMain.getTitle())).collect(Collectors.toList());
                }
            }else{
                LbbMember memberByMemberId = memberMapper.getMemberByMemberId(requestHeaders.getUserid());
                if (memberByMemberId != null) {
                    if (!memberByMemberId.getImei().equals(requestHeaders.getImei())) {
                        list = list.stream().filter(appMain -> !"新手任务".equals(appMain.getTitle())).collect(Collectors.toList());
                    }
                }
            }
        }
        boolean mrbz=downAppService.checkDoRecord(requestHeaders);
        // 过滤新手任务
        if (list != null && requestHeaders.getUserid() != null && !TextUtil.isEmpty(requestHeaders.getUserid())) {
            if(mrbz){
                list = list.stream().filter(appMain -> !"每日必赚".equals(appMain.getTitle())).collect(Collectors.toList());
            }
            LbbMember lbbMember = memberMapper.getMemberByMemberId(requestHeaders.getUserid());
            if (lbbMember != null) {
                if (lbbMember.getCreateTime().before(MEMBER_DATE)) {
                   // log.info("老用户要过滤的");
                    list = list.stream().filter(appMain -> !"新手任务".equals(appMain.getTitle())).collect(Collectors.toList());
                } else {
                    //完成所有新手任务则隐藏新手任务入口
                    TaskRewardsRecord record = taskRewardsRecordMapper.getRecordByMemberIdAndRewardsId(requestHeaders.getUserid(), 1);
                    if (record != null) {
                        //log.info("已经完成所有的任务过滤新手任务");
                        list = list.stream().filter(appMain -> !"新手任务".equals(appMain.getTitle())).collect(Collectors.toList());
                    }
                }

                int i= 0;
                List<String> userTaskList =  lbbMemberRecordMapper.getMemberTaskList(requestHeaders.getUserid());
                for (Iterator<AppMain> iterator = list.iterator(); iterator.hasNext(); ) {
                    AppMain s = iterator.next();
                    if(s.getType()==99){
                        //截图任务
                        if((i>=6)||userTaskList.contains(s.getTask())){
                            //包含完成和失败的,删除
                            iterator.remove();
                        }else{
                            i++;
                        }
                    }

                }

            }
        }
        return list;
    }

    public List<AppMain> selectByType(RequestHeaders requestHeaders,Integer type) {
        boolean mrbz=downAppService.checkDoRecord(requestHeaders);
        List<AppMain> list= appMainMapper.selectByType(requestHeaders.getVersion(),requestHeaders.getAppStore(),type);
        // 过滤新手任务
        if (list != null && requestHeaders.getUserid() != null && !TextUtil.isEmpty(requestHeaders.getUserid())) {
            if(mrbz){
                list = list.stream().filter(appMain -> !"每日必赚".equals(appMain.getTitle())).collect(Collectors.toList());
            }
            LbbMember lbbMember = memberMapper.getMemberByMemberId(requestHeaders.getUserid());
            if (lbbMember != null) {
                if (lbbMember.getCreateTime().before(MEMBER_DATE)) {
                   // log.info("老用户要过滤的");
                    list = list.stream().filter(appMain -> !"新手任务".equals(appMain.getTitle())).collect(Collectors.toList());
                } else {
                    //完成所有新手任务则隐藏新手任务入口
                    TaskRewardsRecord record = taskRewardsRecordMapper.getRecordByMemberIdAndRewardsId(requestHeaders.getUserid(), 1);
                    if(type==1){
                        record =null;
                    }
                    if (record != null) {
                       // log.info("已经完成所有的任务过滤新手任务");
                        list = list.stream().filter(appMain -> !"新手任务".equals(appMain.getTitle())).collect(Collectors.toList());
                    }
                }
            }
        }
        return list;
    }
}
